﻿using MSL.Tool;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Xml;
using TimedTask.Core;
using TimedTask.Models;
using TimedTask.Tools;

namespace TimedTask.Views
{
    /// <summary>
    /// TaskEdit.xaml 的交互逻辑
    /// </summary>
    public partial class TaskEdit : Window
    {
        private RunMode _runMode = 0;
        private string _startTime = "";
        private string _stopTime = "";
        private BLL.AutoTaskBLL _bllTask = new BLL.AutoTaskBLL();
        public Int64 ID { get; set; }

        //窗体加载
        public TaskEdit()
        {
            InitializeComponent();

            foreach (SelectListItem item in SelectLists.TaskTypes)
            {
                this.cboTaskType.Items.Add(item.Text);
            }
            this.btnClose.Click += (s, e) =>
            {
                this.Close();
                Helper.StopAudio();
            };
            this.cboRunType.SelectionChanged += (s, e) =>
            {
                this._runMode = (RunMode)Enum.Parse(typeof(RunMode), this.cboRunType.SelectedValue.ToString());
                RunTypeChanged(s, e);
            };
            this.cboMonth.SelectedIndex = 0;
            this.cboDay.SelectedIndex = 0;
            this.cboMinute.SelectedIndex = 0;
            this.cboTaskType.SelectedIndex = 0;

            this.startTimePicker.Value = DateTime.Now.AddMinutes(5);
            this.endTimePicker.Value = DateTime.Now.AddMinutes(5);
        }
        //窗体初始化
        private void OnInit()
        {
            if (ID == 0)
            {
                this.dp_StartDate.SelectedDate = DateTime.Now;
                this.dp_StopDate.SelectedDate = DateTime.Now.AddDays(10);

                this._runMode = RunMode.Minute;
                RunTypeChanged(null, null);

                return;
            }
            else
            {
                this.cboMinute.SelectedIndex = 0;
            }

            TimedTask.Models.AutoTask model = _bllTask.GetEntity(" Id=" + ID);
            // 开始与停止时间
            this.startTimePicker.Value = model.StartDate;
            this.endTimePicker.Value = model.StopDate;

            if (model != null)
            {
                this.txtPath.Text = model.ApplicationPath;
                this.txtTitle.Text = model.Title;
                this.txtStartParameter.Text = model.StartParameters;
                this.txtRemark.Text = model.Remark;
                this.cboTaskType.SelectedIndex =
                    (model.TaskType == 0 || model.TaskType == (int)TaskType.TimingTask)
                    ? 0
                    : Convert.ToInt32(model.TaskType);

                RunMode runMode = (RunMode)Enum.Parse(typeof(RunMode), model.RunType.ToString());
                this.cboRunType.SelectedValue = model.RunType.ToString();
                this._runMode = runMode;
                switch (runMode)
                {
                    case RunMode.Month:
                        this.cboDay.SelectedValue = model.Dayth;
                        break;
                    case RunMode.Day:
                        break;
                    case RunMode.Hour:
                        break;
                    case RunMode.Minute:
                        this.cboMinute.SelectedValue = model.Interval;
                        break;
                    case RunMode.Once:
                        break;
                    case RunMode.Week:
                        if (model.Weeks != null)
                        {
                            if (model.Weeks.Contains("1")) this.chkWeek1.IsChecked = true;
                            if (model.Weeks.Contains("2")) this.chkWeek2.IsChecked = true;
                            if (model.Weeks.Contains("3")) this.chkWeek3.IsChecked = true;
                            if (model.Weeks.Contains("4")) this.chkWeek4.IsChecked = true;
                            if (model.Weeks.Contains("5")) this.chkWeek5.IsChecked = true;
                            if (model.Weeks.Contains("6")) this.chkWeek6.IsChecked = true;
                            if (model.Weeks.Contains("7")) this.chkWeek7.IsChecked = true;
                        }
                        break;
                }
                RunTypeChanged(null, null);

                this.dp_StartDate.SelectedDate = Convert.ToDateTime(model.StartDate);
                this.dp_StopDate.SelectedDate = Convert.ToDateTime(model.StopDate);
            }
        }
        //窗体加载
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            OnInit();
            //窗体移动
            this.MouseLeftButtonDown += (s, arg) =>
            {
                if (arg.LeftButton == MouseButtonState.Pressed)
                {
                    this.DragMove();
                }
            };

            this.btnClose.Click += (s, arg) =>
            {
                base.Close();
            };
        }
        //浏览文件
        private void btnOpenFile_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = "可执行文件|*.exe";//全部|*.*||批处理|*.bat";
            if (ofd.ShowDialog() == true)
            {
                this.txtPath.Text = ofd.FileName;
            }
        }
        //保存
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            string path = this.txtPath.Text.Trim();
            string title = this.txtTitle.Text.Trim();
            string remark = this.txtRemark.Text.Trim();
            string startParameter = this.txtStartParameter.Text.Trim();
            string startDate = "", stopDate = "", nextStartDate = "";//起始 停止 下次启动时间


            AutoTask model = new AutoTask();
            model.Weeks = "";
            RunMode runMode = (RunMode)Enum.Parse(typeof(RunMode), this.cboRunType.SelectedValue.ToString());
            this._runMode = runMode;

            if (RunMode.Week.Equals(runMode))
            {
                if (GetWeeks().Length == 0)
                {
                    Helper.AlertError("保存失败，没有星期被选中！");
                    return;
                }
                model.Weeks = GetWeeks();
            }
            try
            {
                bool flag = ID == 0 ? true : false;//是否是新增
                if (this.cboTaskType.SelectedIndex == 0)
                {
                    if (path.Length == 0 || !path.EndsWith(".exe"))
                    {
                        Helper.AlertError("不是可执行文件或文件路径不能为空！");
                        return;
                    }
                }

                this._startTime = this.startTimePicker.Value.Value.ToString("HH:mm:ss");// this.cboStartHour.SelectedValue + ":" + startMin + ":00";
                this._stopTime = this.endTimePicker.Value.Value.ToString("HH:mm:ss");// this.cboStopHour.SelectedValue + ":" + stopMin + ":00";

                startDate = this.dp_StartDate.SelectedDate.Value.ToString("yyyy-MM-dd") + " " + this._startTime;
                stopDate = this.dp_StopDate.SelectedDate.Value.ToString("yyyy-MM-dd") + " " + this._stopTime;
                nextStartDate = GetFirstStartDate();

                model.StartParameters = startParameter;
                model.ApplicationPath = path;
                model.Title = title;
                model.StartDate = Convert.ToDateTime(startDate);
                model.StopDate = Convert.ToDateTime(stopDate);
                model.Remark = remark;
                model.TaskType = this.cboTaskType.SelectedIndex;
                model.Status = "";
                model.RunType = (int)this._runMode;

                model.Interval = RunMode.Minute.Equals(runMode) 
                    ? (
                        Convert.ToInt32(this.cboMinute.SelectedValue == null ? this.cboMinute.Text : this.cboMinute.SelectedValue.ToString())
                    ) : 0;
                model.Dayth = RunMode.Month.Equals(runMode) ? Convert.ToInt32(this.cboDay.SelectedValue.ToString()) : 0;
                model.NextStartDate = Convert.ToDateTime(nextStartDate);
                model.BoolEnable = null;

                if (!flag)//修改
                {
                    this._bllTask.Update(model, " Id=" + ID);
                    Helper.AlertSuccess("保存设置成功！" + (DateTime.Now > model.StopDate ? " 警告：任务已过期！" : ""));
                    this.Close();
                }
                else//新增
                {
                    model.Enable = 1;
                    BLL.AutoTaskBLL bllTask = new BLL.AutoTaskBLL();
                    bllTask.Add(model);

                    Helper.AlertSuccess("新增成功！" + (DateTime.Now > model.StopDate ? " 警告：任务已过期！" : ""));
                    btnReset_Click(null, null);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                Helper.AlertError("保存设置失败！");
                LogHelper.SaveErrorLog("TaskEdit btnOK_Click", ex);
            }
        }
        //重置
        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            this.ID = 0;
            this.txtPath.Text = "";
            this.txtRemark.Text = "";
            this.txtStartParameter.Text = "";
            this.txtTitle.Text = "";
            this.cboTaskType.SelectedIndex = 0;

            OnInit();
        }
        //获取首次启动时间
        private string GetFirstStartDate()
        {
            string result = "";
            DateTime nowTime = DateTime.Now;
            string startDate = DateTime.Now.ToString("yyyy-MM-dd");
            if (Convert.ToDateTime(this.dp_StartDate.SelectedDate.Value.ToString("yyyy-MM-dd") + " " + this._startTime) < DateTime.Now)//如果开始时间<当前--->使用当前时间计算下次启动
                startDate = DateTime.Now.ToString("yyyy-MM-dd");

            switch (this._runMode)
            {
                case RunMode.Once://一次
                case RunMode.Day:
                case RunMode.Hour:
                case RunMode.Minute:
                    result = startDate + " " + this._startTime;
                    break;
                case RunMode.Month:
                    result = nowTime.Year + "-" + nowTime.Month + "-" + this.cboDay.SelectedValue + " " + this._startTime;
                    break;
                case RunMode.Week:
                    return TaskManager.GetNextStartDateByWeek(GetWeeks(), Convert.ToDateTime(startDate + " " + this._startTime));
            }
            result = Convert.ToDateTime(result).ToString("yyyy-MM-dd HH:mm:ss");
            if (Convert.ToDateTime(result) < DateTime.Now)
            {
                string interval = RunMode.Minute.Equals(this._runMode) ? this.cboMinute.SelectedValue.ToString() : "0";
                string dayth = RunMode.Month.Equals(this._runMode) ? this.cboDay.SelectedValue.ToString() : "0";

                RunMode runMode = (RunMode)Enum.Parse(typeof(RunMode), this._runMode.ToString());
                result = TaskManager.GetNextStartDateByType(DateTime.Parse(result), runMode, Convert.ToInt32(dayth), null, Convert.ToInt32(interval));
            }
            return result;
        }
        //选中的星期
        private string GetWeeks()
        {
            string weeks = String.Empty;
            if (this.chkWeek1.IsChecked == true) weeks += "1|";
            if (this.chkWeek2.IsChecked == true) weeks += "2|";
            if (this.chkWeek3.IsChecked == true) weeks += "3|";
            if (this.chkWeek4.IsChecked == true) weeks += "4|";
            if (this.chkWeek5.IsChecked == true) weeks += "5|";
            if (this.chkWeek6.IsChecked == true) weeks += "6|";
            if (this.chkWeek7.IsChecked == true) weeks += "7|";
            if (weeks.Length > 0)
                weeks = weeks.Remove(weeks.Length - 1);

            return weeks;
        }
        //运行周期
        private void RunTypeChanged(object sender, RoutedEventArgs e)
        {
            this.cboMonth.IsEnabled = true;
            this.cboDay.IsEnabled = true;
            this.dp_StartDate.IsEnabled = true;
            this.dp_StopDate.IsEnabled = true;
            this.cboMinute.IsEnabled = true;

            this.startTimePicker.IsEnabled = true;
            this.endTimePicker.IsEnabled = true;

            this.spWeek.Visibility = Visibility.Collapsed;
            this.spMode.Visibility = Visibility.Visible;

            switch (this._runMode)
            {
                case RunMode.Year:
                    break;
                case RunMode.Month:
                    this.cboMonth.IsEnabled = false;
                    this.cboMinute.IsEnabled = false;
                    this.dp_StartDate.IsEnabled = false;
                    break;
                case RunMode.Day:
                    this.cboMonth.IsEnabled = false;
                    this.cboDay.IsEnabled = false;
                    this.dp_StartDate.IsEnabled = false;
                    this.cboMinute.IsEnabled = false;
                    break;
                case RunMode.Hour:
                    this.cboMonth.IsEnabled = false;
                    this.cboDay.IsEnabled = false;
                    this.cboMinute.IsEnabled = false;
                    this.dp_StartDate.IsEnabled = false;
                    break;
                case RunMode.Minute:
                    this.cboMonth.IsEnabled = false;
                    this.cboDay.IsEnabled = false;
                    break;
                case RunMode.Once:
                    this.cboMonth.IsEnabled = false;
                    this.cboDay.IsEnabled = false;
                    this.dp_StopDate.IsEnabled = false;
                    this.cboMinute.IsEnabled = false;
                    this.endTimePicker.IsEnabled = false;
                    break;
                case RunMode.Week:
                    this.cboMonth.IsEnabled = false;
                    this.cboDay.IsEnabled = false;
                    this.cboMinute.IsEnabled = false;
                    this.spWeek.Visibility = Visibility.Visible;
                    this.spMode.Visibility = Visibility.Collapsed;
                    break;
                default:
                    break;
            }
        }
        //任务类型
        private void cboTaskType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.cboTaskType.SelectedIndex != 0)
            {
                this.txtPath.IsEnabled = false;
                this.txtStartParameter.IsEnabled = false;
                this.btnOpenFile.IsEnabled = false;
                if (this.txtTitle.Text.Length == 0)
                {
                    this.txtTitle.Text = this.cboTaskType.SelectedValue.ToString();
                    this.txtRemark.Text = "开启" + this.cboTaskType.SelectedValue.ToString();
                }
            }
            else//定时任务
            {
                this.txtPath.IsEnabled = true;
                this.txtStartParameter.IsEnabled = true;
                this.btnOpenFile.IsEnabled = true;
                if (this.txtTitle.Text.StartsWith("定时")) this.txtTitle.Text = "";
            }
        }
    }
}
